/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.erp.erp.security.logic;

import com.erp.erp.security.pojo.Companies;
import com.erp.erp.security.pojo.CompanyModuleForms;
import com.erp.erp.security.pojo.CompanyModuleReports;
import com.erp.erp.security.pojo.CompanyModules;
import com.erp.erp.security.pojo.CompanyRoles;
import com.erp.erp.security.pojo.Forms;
import com.erp.erp.security.pojo.Modules;
import com.erp.erp.security.pojo.Reports;
import com.erp.erp.security.pojo.Stores;
import com.erp.erp.security.pojo.UserCompanies;
import com.erp.erp.security.pojo.UserRoles;
import com.erp.erp.security.pojo.UserStoresPrivileges;
import com.erp.erp.security.pojo.Users;
import com.erp.erp.security.util.HibernateUtil;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author maha
 */
public class SecurityLogic {

    Session session;

    public SecurityLogic() {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    public Users login(String userCode, String userPassword) {
        Users u = new Users();
        //===========Encrypt Upcomign userpassword========================
        userPassword = Ciphers.getEncryptedTextUsingMD5(userPassword);
        //================================================================
        Iterator iterator = session.createCriteria(Users.class).add(Restrictions.ilike("userCode", userCode, MatchMode.EXACT)).add(Restrictions.ilike("userPassword", userPassword, MatchMode.EXACT)).list().iterator();
        while (iterator.hasNext()) {
            u = (Users) iterator.next();
        }
        if (u != null) {

            if (u.getLogin() == true) {
                u = null;
            } else {
                session.getTransaction().begin();
                String hql = "update Users set  login= :login where userCode=:code and userSid=:id";
                Query query = session.createQuery(hql);
                query.setBoolean("login", true);
                query.setString("code", userCode);
                query.setInteger("id", u.getUserSid());
                int x = query.executeUpdate();
                System.out.println("Changing state =" + x);
                session.getTransaction().commit();
            }
        }
        return u;
    }

    public int logOut(int userId, String userCode) {
        session.getTransaction().begin();
        String hql = "update Users set  login= :login,lastTimeCheck=:check where userCode=:code and userSid=:id";
        Query query = session.createQuery(hql);
        query.setBoolean("login", false);
        query.setString("code", userCode);
        query.setInteger("id", userId);

        Date dt = new Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        query.setString("check", currentTime);
        int x = query.executeUpdate();
        System.out.println("Changing state =" + x);
        session.getTransaction().commit();
        return x;
    }

    // 0 = error occured, 1= successfuly done , 2= already exists
    public int register(Users user) {
        int x = 0;
        try {
            session.getTransaction().begin();
            Users u = new Users();
            Iterator iterator = session.createCriteria(Users.class).add(Restrictions.ilike("userCode", user.getUserCode(), MatchMode.EXACT)).list().iterator();
            while (iterator.hasNext()) {
                u = (Users) iterator.next();
            }
            if (u.getUserCode() == null) {
                //============Encrypt Password=================
                String encryptedTextUsingMD5 = Ciphers.getEncryptedTextUsingMD5(user.getUserPassword());
                user.setUserPassword(encryptedTextUsingMD5);
                //=============================================
                session.save(user);
                x = 1;
            } else {
                x = 2;
            }
            session.getTransaction().commit();
        } catch (Exception ex) {
            System.out.println("Exception Occured in register method in SecurityLogic Class");
            ex.printStackTrace();
        }
        return x;
    }

    public Users getUser(String userCode) {
        Users u = null;
        Iterator iterator = session.createCriteria(Users.class).add(Restrictions.ilike("userCode", userCode, MatchMode.EXACT)).list().iterator();
        while (iterator.hasNext()) {
            u = (Users) iterator.next();
        }
        return u;
    }

    public Vector<Companies> getCompanies() {
        Vector<Companies> companies = new Vector<Companies>();
        Iterator iterator = session.createCriteria(Companies.class).list().iterator();
        while (iterator.hasNext()) {
            companies.add((Companies) iterator.next());

        }

        return companies;
    }

    public int addCompany(Companies company) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(company);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompany in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public int addStore(Stores store) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(store);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompany in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }
//===========================================================================================

    public Vector<UserCompanies> getUserCompanies(int UserId) {
        Vector<UserCompanies> userCompany = new Vector<UserCompanies>();
        Iterator iterator = session.createCriteria(UserCompanies.class).add(Restrictions.eq("usersByUserSid.userSid", UserId)).list().iterator();
        while (iterator.hasNext()) {
            userCompany.add((UserCompanies) iterator.next());

        }
        return userCompany;
    }

    public Companies getCompany(int companyId) {
        Companies company = null;
        Iterator iterator = session.createCriteria(Companies.class).add(Restrictions.eq("companySid", companyId)).list().iterator();
        while (iterator.hasNext()) {
            company = (Companies) iterator.next();

        }
        return company;
    }

    public Vector<Modules> getModules() {
        Vector<Modules> modules = new Vector<Modules>();
        Iterator iterator = session.createCriteria(Modules.class).list().iterator();
        while (iterator.hasNext()) {
            modules.add((Modules) iterator.next());

        }
        return modules;
    }

    public int addModule(Modules module) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(module);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addModule in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public int addCompanyModule(CompanyModules modules) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(modules);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompanyModule in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }
    //=============================================================================

    public int addUserCompany(UserCompanies userCompany) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(userCompany);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addUserCompany in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public Vector<Users> getUsers() {
        Vector<Users> users = new Vector<Users>();
        Iterator iterator = session.createCriteria(Users.class).list().iterator();
        while (iterator.hasNext()) {
            users.add((Users) iterator.next());

        }
        return users;
    }
//=======================================================================================

    //=========Tested, Woking fine================
    public Vector<CompanyRoles> getCompanyRoles(int companyId) {
        Vector<CompanyRoles> companyRoles = new Vector<CompanyRoles>();
        Iterator iterator = session.createCriteria(CompanyRoles.class).createAlias("companyModules", "c").add(Restrictions.eq("c.companies.companySid", companyId)).list().iterator();
        while (iterator.hasNext()) {
            companyRoles.add((CompanyRoles) iterator.next());

        }
        return companyRoles;
    }

    public Vector<Stores> getCompanyStores(int companyId) {
        Vector<Stores> stores = new Vector<Stores>();
        Iterator iterator = session.createCriteria(Stores.class).add(Restrictions.eq("companies.companySid", companyId)).list().iterator();
        while (iterator.hasNext()) {
            stores.add((Stores) iterator.next());
        }
        return stores;
    }
    //=================================================================================

    public int getUserCompanySID(int userId, int companyId) {
        int x = 0;
        Iterator iterator = session.createCriteria(UserCompanies.class).add(Restrictions.eq("usersByUserSid.userSid", userId)).add(Restrictions.eq("companies.companySid", companyId)).list().iterator();
        while (iterator.hasNext()) {
            UserCompanies object = (UserCompanies) iterator.next();
            x = object.getUserCompanySid();
        }
        return x;
    }

    public int addUserRoles(UserRoles userRoles) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(userRoles);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in userRoles in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public int addUserStorePriv(UserStoresPrivileges userStorePriv) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(userStorePriv);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addUserStorePriv in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public Vector<CompanyModules> getCompanyModules(int companyId) {
        Vector<CompanyModules> cmodule = new Vector<CompanyModules>();
        Iterator iterator = session.createCriteria(CompanyModules.class).add(Restrictions.eq("companies.companySid", companyId)).list().iterator();
        while (iterator.hasNext()) {
            CompanyModules object = (CompanyModules) iterator.next();
            cmodule.add(object);
        }
        return cmodule;
    }

    public Vector<Forms> getModuleForms(int moduleId) {
        Vector<Forms> cmodule = new Vector<Forms>();
        Iterator iterator = session.createCriteria(Forms.class).add(Restrictions.eq("modules.moduleSid", moduleId)).list().iterator();
        while (iterator.hasNext()) {
            Forms object = (Forms) iterator.next();
            cmodule.add(object);
        }
        return cmodule;
    }

    public Vector<Reports> getModuleReports(int moduleId) {
        Vector<Reports> cmodule = new Vector<Reports>();
        Iterator iterator = session.createCriteria(Reports.class).add(Restrictions.eq("modules.moduleSid", moduleId)).list().iterator();
        while (iterator.hasNext()) {
            Reports object = (Reports) iterator.next();
            cmodule.add(object);
        }
        return cmodule;
    }

    public int addCompanyModuleForm(CompanyModuleForms c) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(c);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompanyModuleForm in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public int addCompanyModuleReport(CompanyModuleReports c) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(c);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompanyModuleReport in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public int getCompanyModuleSid(int moduleId, int companyId) {
        int x = 0;
        Iterator iterator = session.createCriteria(CompanyModules.class).add(Restrictions.eq("modules.moduleSid", moduleId)).add(Restrictions.eq("companies.companySid", companyId)).list().iterator();
        while (iterator.hasNext()) {
            CompanyModules object = (CompanyModules) iterator.next();
            x = object.getCompanyModuleSid();
        }
        return x;
    }
//==========================================================

    public int addCompanyRole(CompanyRoles roles) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(roles);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompanyRole in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public int addCompanyRoleForm(CompanyModuleForms form) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(form);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompanyRoleForm in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }

    public int addCompanyRoleReport(CompanyModuleReports report) {
        int x;
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(report);
            session.getTransaction().commit();
            x = 1;
        } catch (Exception ex) {
            x = 0;
            System.out.println("Exception Occured in addCompanyRoleReport in class SecurityLogic");
            ex.printStackTrace();
        }
        return x;
    }
}
